package com.javawork.juc.three;

import java.util.concurrent.TimeUnit;

/**
 * 1.中断标志位，默认false<br/>
 * 2.t2-->t1发出了中断协商，t2调用t1.interrupt（），中断标志位true<br/>
 * 3.中断标志位true，正常情况，程序停止<br/>
 * 4.中断标志位true，异常情况，InterruptedException，将会把中断状态将被清除，并将收到班InterruptedException。中断标志false,导致无限循环<br/>
 * 5.在catch块中，需要再次给中所标志位设置为true，2次调用停止程序才ok<br/>
 * @author zhangxiaolu
 * @since 2023-02-08 23:15
 */
public class InterruptDemo3 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "中断标志位：" + Thread.currentThread().isInterrupted() + "，程序停止");
                    break;
                }
                //
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();//为什么调用两次？？
                }
                System.out.println("t1----hello InterruptDemo3");
            }
        }, "t1");
        t1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(t1::interrupt, "t2").start();
    }
}
